<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['factory:garment-style:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['factory:garment-style:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="自增主键" prop="id" min-width="150" align="center" />
        <el-table-column
          key="styleCode"
          label="款号（唯一标识，如FW2024-001）"
          prop="styleCode"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="styleName"
          label="款名称（如休闲廓形衬衫）"
          prop="styleName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="styleNotes"
          label="款备注（特殊工艺/面料说明）"
          prop="styleNotes"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="color"
          label="颜色（可多选，用逗号分隔，如白色,藏青）"
          prop="color"
          min-width="150"
          align="center"
        />
        <el-table-column key="size" label="码数" prop="size" min-width="150" align="center" />
        <el-table-column
          key="outsourcedPrice"
          label="外发价格（单位：元）"
          prop="outsourcedPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="employeePrice"
          label="员工价格（单位：元）"
          prop="employeePrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="cuttingPrice"
          label="裁床价（单位：元）"
          prop="cuttingPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="imageUrl"
          label="款图片URL"
          prop="imageUrl"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="category"
          label="分类"
          prop="category"
          min-width="150"
          align="center"
        />
        <el-table-column align="center" label="状态" width="150">
          <template #default="scope">
            <DictLabel v-model="scope.row.status" :code="'\t\n' + 'garment_style_status'" />
          </template>
        </el-table-column>
        <el-table-column
          key="createBy"
          label="创建人ID"
          prop="createBy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateBy"
          label="修改人ID"
          prop="updateBy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['factory:garment-style:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['factory:garment-style:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 服装款式表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="160px">
        <el-form-item label="款号" prop="styleCode">
          <el-input v-model="formData.styleCode" placeholder="款号（唯一标识，如FW2024-001）" />
        </el-form-item>

        <el-form-item label="款名称" prop="styleName">
          <el-input v-model="formData.styleName" placeholder="款名称（如休闲廓形衬衫）" />
        </el-form-item>

        <el-form-item label="款备注" prop="styleNotes">
          <el-input v-model="formData.styleNotes" placeholder="款备注（特殊工艺/面料说明）" />
        </el-form-item>

        <el-form-item label="颜色" prop="color">
          <el-select v-model="formData.color" placeholder="颜色" clearable filterable multiple>
            <el-option
              v-for="item in colorOptions"
              :label="item.colorName"
              :value="item.colorId.toString()"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="码数" prop="size">
          <el-select
            v-model="formData.size"
            placeholder="码数"
            clearable
            filterable
            multiple
            remote
            :remote-method="getSizeOptions"
            @change="sizeChange"
          >
            <el-option
              v-for="item in sizeOptions"
              :label="item.sizeCode"
              :value="item.id.toString()"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="裁床价（单位：元）" prop="cuttingPrice">
          <el-input v-model="formData.cuttingPrice" placeholder="裁床价（生产成本，单位：元）" />
        </el-form-item>

        <el-form-item label="外发价格（单位：元）" prop="outsourcedPrice">
          <el-input
            v-model="formData.outsourcedPrice"
            placeholder="外发价格（外发加工单价，单位：元）"
          />
        </el-form-item>

        <el-form-item label="员工价格（单位：元）" prop="employeePrice">
          <el-input
            v-model="formData.employeePrice"
            placeholder="员工价格（员工购买价格，单位：元）"
          />
        </el-form-item>

        <el-form-item label="款图片URL" prop="imageUrl">
          <el-input v-model="formData.imageUrl" placeholder="款图片URL（存储图片路径或链接）" />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-input v-model="formData.category" placeholder="分类（如上衣/裤装/连衣裙）" />
        </el-form-item>

        <el-form-item label="状态：开发中/在售/停售/缺货" prop="status">
          <Dict v-model="formData.status" code="garment_style_status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import ColorAPI, { ColorPageVO } from "@/api/factory/color";

defineOptions({
  name: "GarmentStyle",
  inheritAttrs: false,
});

import GarmentStyleAPI, {
  GarmentStylePageVO,
  GarmentStyleForm,
  GarmentStylePageQuery,
} from "@/api/factory/garment-style";
import ClothingSizesAPI, { ClothingSizesPageVO } from "@/api/factory/clothing-sizes";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<GarmentStylePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 服装款式表格数据
const pageData = ref<GarmentStylePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 服装款式表单数据
const formData = reactive<GarmentStyleForm>({});

// 服装款式表单校验规则
const rules = reactive({
  styleCode: [{ required: true, message: "请输入款号（唯一标识，如FW2024-001）", trigger: "blur" }],
  styleName: [{ required: true, message: "请输入款名称（如休闲廓形衬衫）", trigger: "blur" }],
  color: [
    { required: true, message: "请输入颜色（可多选，用逗号分隔，如白色,藏青）", trigger: "blur" },
  ],
  size: [{ required: true, message: "请输入码数（可多选，用逗号分隔，如S,M,L）", trigger: "blur" }],
  unitPrice: [{ required: true, message: "请输入单价（零售价，单位：元）", trigger: "blur" }],
  status: [{ required: true, message: "请输入状态：开发中/在售/停售/缺货", trigger: "blur" }],
});

/** 查询服装款式 */
function handleQuery() {
  loading.value = true;
  GarmentStyleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置服装款式查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开服装款式弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改服装款式";
    GarmentStyleAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
      formData.size = data.size ? data.size.split(",") : [];
      formData.color = data.color ? data.color.split(",") : [];
    });
  } else {
    dialog.title = "新增服装款式";
  }
}

/** 提交服装款式表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        GarmentStyleAPI.update(id, {
          ...formData,
          size:
            formData.size && Array.isArray(formData.size) && formData.size.length > 0
              ? formData.size.join(",")
              : null,
          color:
            formData.color && Array.isArray(formData.color) && formData.color.length > 0
              ? formData.color.join(",")
              : null,
        })
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        GarmentStyleAPI.add({ ...formData, size: formData.size?.join(",") })
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭服装款式弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除服装款式 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      GarmentStyleAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

const colorOptions = ref<ColorPageVO[]>();

//获取颜色选项
async function getColorOptions() {
  const res = await ColorAPI.getPage();
  console.log(res, "res事什么");
  colorOptions.value = res.list;
}

const sizeOptions = ref<ClothingSizesPageVO[]>();

//获取颜色选项
async function getSizeOptions(sizeCode: string) {
  const res = await ClothingSizesAPI.getPage({ sizeCode });
  sizeOptions.value = res.list;
}

async function sizeChange(e) {
  console.log(e, "尺码变化");
}

onMounted(() => {
  handleQuery();
  getColorOptions();
  // getSizeOptions("");
});
</script>
